/**
 *
 */
package name.yzhu.httpserver;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import name.yzhu.common.service.Stoppable;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * System management servlet for http server
 * @author yhzhu
 *
 */
public class AdminServlet extends AbstractHttpServlet implements IServerAdminable{
	private static final Log LOG = LogFactory.getLog(AdminServlet.class);
	private Stoppable stop = null;
	/**
	 *
	 */
	private static final long serialVersionUID = 2932747414011735013L;

	private List<AbstractHttpServlet> servlets = new ArrayList<AbstractHttpServlet>();

	public void setStoppable(Stoppable s) {
		stop = s;
	}
	@Override
	public String getContextRoot() {
		return "/";
	}

	@Override
	public String getContextPath() {
		return "/admin";
	}

	@Override
	protected void process(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String cmd = req.getParameter("cmd");
		LOG.debug("cmd="+cmd);
		if (cmd != null && cmd.equals("stop")) {
			stop.stop();
			resp.getWriter().print(HttpServerUtil.format("Admin", "The server is stopped"));
		}
		else if (cmd != null && cmd.equals("list")) {
			StringBuilder sb = new StringBuilder();
			for (AbstractHttpServlet s : getServlets()){
				if (s.getContextPath().equals("/"))
					continue;

				String url = "http://"+req.getLocalName()+":"+req.getLocalPort();
				if (!s.getContextRoot().equals("/"))
						url += s.getContextRoot();
				url += s.getContextPath();

				sb.append("<a href=\""+url+"\">"+url+"</a> <br>");
			}
			resp.getWriter().print(HttpServerUtil.format("default", sb.toString()));
		}
		else {
			resp.getWriter().print("Invalid admin command");
		}
	}

	public void addServlet(AbstractHttpServlet servlet) {
		servlets.add(servlet);
	}
	public List<AbstractHttpServlet> getServlets() {
		return servlets;
	}
}
